<template>
  <div>
    <!-- 管理容器组件 -->
    <admin-container>
      <template v-slot:content>
        <!-- 表格插件 -->
        <table-plugin
          :page="page"
          :config="config"
          :part-operate="partOperate"
          :global-operate="globalOperate"
          :search-operate="searchOperate"
          @part="partOperateActuator"
          @search="searchOperateActuator"
          @global="globalOperateActuator"
        />
      </template>
    </admin-container>

    <!-- 抽屉组件 -->
    <el-drawer
      :title="drawer.title"
      :visible.sync="drawer.flag"
      @close="
        $refs['advertRef'].clearValidate();
        advert = {};
        upload.fileList = [];
      "
      size="50%"
    >
      <div class="drawer-main">
        <!-- 表单组件 -->
        <el-form
          :model="advert"
          ref="advertRef"
          label-width="110px"
          :rules="rules"
        >
          <el-form-item label="广告标语" prop="slogan">
            <el-input v-model="advert.slogan" placeholder="请输入广告标语" />
          </el-form-item>
          <el-form-item label="第三方链接" prop="href">
            <el-input v-model="advert.href" placeholder="请输入广告跳转链接" />
          </el-form-item>
          <el-form-item label="广告类型" prop="type">
            <el-select v-model="advert.type">
              <el-option
                :label="item.name"
                :value="item.type"
                v-for="(item, index) in advertTypeList"
                :key="index"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="广告素材上传" v-if="advert.type != 3" prop="url">
            <el-upload
              drag
              v-model="advert.url"
              :action="upload.action"
              :multiple="upload.multiple"
              :fileList="upload.fileList"
              :name="upload.name"
              :on-success="uploadSuccessHandler"
              :limit="1"
              :on-exceed="uploadExceedHandler"
              :before-upload="uploadBeforeHandler"
              @submit="uploadFile"
              :accept="upload.accept"
              :on-error="uploadErrorHandler"
              :headers="upload.headers"
              :on-remove="uploadRemove"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                只能上传jpg/png/mp4文件，且不超过20Mb
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="备注" class="deep-textarea">
            <el-input type="textarea" autosize v-model="advert.remarks" />
          </el-form-item>
        </el-form>

        <div class="drawer-btn">
          <el-button type="primary" size="medium" @click="saveOrUpdate"
            >确定提交</el-button
          >
          <el-button size="medium" @click="drawer.flag = false">取消</el-button>
        </div>
      </div>
    </el-drawer>
    <el-dialog
      :visible.sync="dialog.flag"
      :title="dialog.title"
      @close="dialogClosHandler"
    >
      <div
        style="
          height: 300px;
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        <el-image
          style="width: 480px; height: 260px"
          :src="dialog.content"
          v-if="dialog.type === 1"
        ></el-image>
        <div v-html="dialog.content" v-if="dialog.type === 2"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AdminContainer from "@/components/plugs/admin-container/AdminContainer.vue";
import TablePlugin from "@/components/plugs/table-plugin/TablePlugin.vue";
import { post, get } from "@/utils/api";
import { rules } from "@/utils/rules";
export default {
  data() {
    let validFile = (rule, value, callback) => {
      if (!value) {
        return callback("广告素材不能为空");
      }
      return callback();
    };
    let validHerf = (rule, value, callback) => {
      if (!rules.url.test(value)) {
        return callback("第三方链接格式错误，必须是http请求或者https请求");
      }
      return callback();
    };
    return {
      upload: {
        multiple: false,
        action: "https://api.sns.qugeek.com/base-file/file/upload",
        accept: ".png,.jpg,.mp4",
        headers: {},
        fileList: [],
      },

      drawer: {
        flag: false,
        title: "",
        name: "file",
      },
      dialog: {
        flag: false,
        title: "",
        content: "",
        type: "",
      },
      advert: {},
      rules: {
        slogan: [
          { required: true, message: "广告词不能为空", trigger: "blur" },
        ],
        href: [
          { required: true, message: "第三方链接不能为空", trigger: "blur" },
          { required: true, validator: validHerf, trigger: "blur" },
        ],
        type: [
          { required: true, message: "广告类型不能为空", trigger: "blur" },
        ],
        url: [{ required: true, validator: validFile, trigger: "blur" }],
      },
      advertTypeList: [],
      page: {
        current: 1,
        size: 10,
        total: 0,
        records: [],
      },
      config: {
        columns: [
          {
            fixed: false,
            prop: "id",
            label: "编号",
            width: "150",
          },
          {
            fixed: false,
            prop: "slogan",
            label: "标语",
            width: "150",
          },
          {
            fixed: false,
            prop: "publisher",
            label: "发布者",
            width: "150",
          },
          {
            fixed: false,
            prop: "href",
            label: "跳转第三方链接",
            width: "200",
          },
          {
            fixed: false,
            prop: "url",
            label: "广告链接",
            width: "200",
          },
          {
            fixed: false,
            prop: "typeName",
            label: "广告类型",
            width: "150",
          },
          {
            fixed: false,
            prop: "remarks",
            label: "备注",
            width: "150",
          },
        ],
      },
      partOperate: [
        { type: "preview", text: "预览", level: "text", color: "" },
        { type: "update", text: "修改", level: "text", color: "" },
        { type: "delete", text: "删除", level: "text", color: "red" },
      ],
      searchOperate: {
        entity: {},
        condition: [
          {
            label: "广告标语",
            prompt: "查询广告标语(模糊查询)",
            type: "input",
            width: "300px",
            name: "slogan",
          },
        ],
      },
      globalOperate: {
        left: [{ type: "add", text: "发布广告", level: "primary", icon: "" }],
        right: [],
      },
    };
  },
  methods: {
    // 部分操作执行器
    partOperateActuator(index, row, operate) {
      switch (operate.type) {
        case "update":
          this.showDataInfo(row);
          break;
        case "delete":
          this.deleteAdvert(row);
          break;
        case "preview":
          this.previewAdvertContent(row);
          break;
      }
    },
    // 全局操作执行器
    globalOperateActuator(entity) {
      switch (entity.operate.type) {
        case "add":
          this.drawer.flag = true;
          this.drawer.title = "发布新广告";
          break;
      }
    },
    // 搜索操作执行器
    searchOperateActuator() {
      this.getPage();
    },
    // 获取分页数据
    getPage() {
      const promise = get({
        url: "/base-advert/back/advert/page",
        params: {
          current: this.page.current,
          size: this.page.size,
          slogan: this.searchOperate.entity.slogan,
        },
      });
      promise.then((res) => {
        if (res && res.code === 200) {
          this.page = res.data;
        }
      });
    },
    // 删除广告
    deleteAdvert(row) {
      const promise = post({
        url: "/base-advert/back/advert/delete",
        data: { id: row.id },
      });

      promise.then((res) => {
        if (res && res.code === 200) {
          this.$message.success(res.message);
          this.getPage();
          return;
        }
        this.$message.error(res.message);
      });
    },
    // 预览广告内容
    previewAdvertContent(row) {
      this.$nextTick(() => {
        if (row.type == 2) {
          this.dialog.content = `<video style="width: 480px;height: 260px;"  controls id="video-dom"><source src="${row.url}" type="video/mp4" /></video>`;
        } else {
          this.dialog.content = row.url;
        }

        this.dialog.type = row.type;
        this.dialog.title = `预览《${row.slogan}》`;
        this.dialog.flag = true;
      });
    },
    // 提交保存或更新
    saveOrUpdate() {
      this.$refs["advertRef"].validate((valid) => {
        if (valid) {
          const promise = post({
            url: "/base-advert/back/advert/save-or-update",
            data: { ...this.advert },
          });
          promise.then((res) => {
            if (res && res.code === 200) {
              this.$message.success(res.message);
              this.getPage();
              this.drawer.flag = false;
              return;
            }
            this.$message.error(res.message);
          });
        } else {
          this.$message.error("表单数据校验不通过，请检查后重试~");
        }
      });
    },
    // 广告素材上传成功处理
    uploadSuccessHandler(response, file, fileList) {
      this.upload.fileList.push({
        name: response.data.originalFilename,
        url: response.data.link,
      });
      this.advert.url = response.data.link;
    },
    // 广告素材上传数量超过限制处理
    uploadExceedHandler(files, fileList) {
      this.$message.error("最多只能上传一个广告素材");
    },
    // 广告素材上传文件处理
    uploadFile() {},
    // 广告素材上传前处理
    uploadBeforeHandler(file) {
      let flag = false;
      if (this.upload.fileList.length > 0) {
        this.$message.error("最多只能上传一个文件");
        return flag;
      }
      switch (file.type) {
        case "image/png":
          flag = true;
          break;
        case "image/jpeg":
          flag = true;
          break;
        case "video/mp4":
          flag = true;
          break;
      }
      if (!flag) {
        this.$message.error("只支持jpg,png的图片和mp4的视频上传~");
      }
      return flag;
    },
    // 广告素材上传错误处理
    uploadErrorHandler(err, file, fileList) {
      this.$message.error(err.message);
    },
    // 对话框关闭处理
    dialogClosHandler() {
      if (this.dialog.type === 2) {
        document.querySelector("#video-dom").pause();
      }
    },
    // 移除已上传的文件
    uploadRemove(file, fileList) {
      this.upload.fileList = [];
      this.advert.url = null;
    },
    // 获取广告类型列表
    getAdvertTypeList() {
      const promise = get({
        url: "/base-advert/back/advert/type/list",
      });

      promise.then((res) => {
        if (res && res.code === 200) {
          this.advertTypeList = res.data;
        }
      });
    },
    // 显示广告信息以进行更新
    showDataInfo(row) {
      if (row.type != 3) {
        const promise = get({
          url: "/base-file/file/info",
          params: { fileUrl: row.url },
        });

        promise.then((res) => {
          if (res && res.code === 200) {
            this.$nextTick(() => {
              this.$set(this.upload.fileList, 0, res.data);
              this.advert = JSON.parse(JSON.stringify(row));
              this.drawer.flag = true;
              this.drawer.title = "修改广告信息信息";
            });
          }
        });
      } else {
        this.advert = JSON.parse(JSON.stringify(row));
        this.drawer.flag = true;
        this.drawer.title = "修改广告信息信息";
      }
    },
  },
  components: {
    AdminContainer,
    TablePlugin,
  },
  created() {
    const token = localStorage.getItem("token");
    this.upload.headers = { Authorization: token };
    this.getPage();
    this.getAdvertTypeList();
  },
};
</script>

<style scoped>
.drawer-main {
  padding-left: 20px;
  padding-right: 20px;
  position: relative;
  padding-bottom: 50px;
}

.drawer-btn {
  position: fixed;
  bottom: 0;
  padding-bottom: 20px;
}

.deep-textarea >>> textarea {
  max-height: 50px;
}
</style>
